package com.bwc.codevideo

import android.animation.ObjectAnimator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import com.google.gson.annotations.SerializedName
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Body
import retrofit2.http.Header
import retrofit2.http.POST
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.Objects

class RunningActivity : AppCompatActivity() {
    private var cb_is_target : CheckBox ?= null
    private var et_current_distance : EditText?= null
    private var et_current_speed : EditText?= null
    private var et_current_heart : EditText?= null
    private var et_current_calorie : EditText?= null
    private var et_current_frequency : EditText?= null
    private var et_target_distance : EditText?= null
    private var et_target_speed : EditText?= null
    private var et_target_heart : EditText?= null
    private var et_target_calorie : EditText?= null
    private var et_target_frequency : EditText?= null
    private var btn_send_ai : Button ?= null
    private var tv_output_ai : TextView ?= null
    private var tv_target : TextView ?= null

    private var running : Boolean = true
    private var target : Boolean = false

    private var current_distance : String ?= null
    private var current_speed : String ?= null
    private var current_heart : String ?= null
    private var current_calorie : String ?= null
    private var current_frequency : String ?= null
    private var target_distance : String ?= null
    private var target_speed : String ?= null
    private var target_heart : String ?= null
    private var target_calorie : String ?= null
    private var target_frequency : String ?= null

    val handler = Handler(Looper.getMainLooper())  // 用于在主线程更新 UI
    var currentIndex = 0  // 用于追踪当前字符的索引

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_running)
        cb_is_target = findViewById(R.id.cb_is_target)
        et_current_distance = findViewById(R.id.et_current_distance)
        et_current_speed = findViewById(R.id.et_current_speed)
        et_current_heart = findViewById(R.id.et_current_heart)
        et_current_calorie = findViewById(R.id.et_current_calorie)
        et_current_frequency = findViewById(R.id.et_current_frequency)
        et_target_distance = findViewById(R.id.et_target_distance)
        et_target_speed = findViewById(R.id.et_target_speed)
        et_target_heart = findViewById(R.id.et_target_heart)
        et_target_calorie = findViewById(R.id.et_target_calorie)
        et_target_frequency = findViewById(R.id.et_target_frequency)
        btn_send_ai = findViewById(R.id.btn_send_ai)
        tv_output_ai = findViewById(R.id.tv_output_ai)
        tv_target = findViewById(R.id.tv_target)


        cb_is_target?.isChecked = target
        setTarget(cb_is_target?.isChecked!!)


        cb_is_target?.setOnCheckedChangeListener { _, isChecked ->
            Log.d("RunningActivity---", "onCreate: ,$isChecked")
            target = isChecked
            setTarget(target)
        }

        onChangeText()
        sendAi()
    }

    private fun onChangeText() {
        et_current_distance?.addTextChangedListener { text ->
            Log.d("RunningActivity---", "et_current_distance: $text")
            current_distance = text.toString()
        }
        et_current_speed?.addTextChangedListener { text ->
            Log.d("RunningActivity---", "et_current_speed: $text")
            current_speed = text.toString()
        }
        et_current_heart?.addTextChangedListener { text ->
            Log.d("RunningActivity---", "et_current_heart: $text")
            current_heart = text.toString()
        }
        et_current_frequency?.addTextChangedListener { text ->
            Log.d("RunningActivity---", "et_current_frequency: $text")
            current_frequency = text.toString()
        }
        et_current_calorie?.addTextChangedListener { text ->
            Log.d("RunningActivity---", "et_current_calorie: $text")
            current_calorie = text.toString()
        }
        et_target_distance?.addTextChangedListener { text ->
            Log.d("RunningActivity---", "et_target_distance: $text")
            target_distance = text.toString()
        }
        et_target_speed?.addTextChangedListener { text ->
            Log.d("RunningActivity---", "et_target_speed: $text")
            target_speed = text.toString()
        }
        et_target_heart?.addTextChangedListener { text ->
            Log.d("RunningActivity---", "et_target_heart: $text")
            target_heart = text.toString()

        }
        et_target_frequency?.addTextChangedListener { text ->
            Log.d("RunningActivity---", "et_target_frequency: $text")
            target_frequency = text.toString()
        }
        et_target_calorie?.addTextChangedListener { text ->
            Log.d("RunningActivity---", "et_target_calorie: $text")
            target_calorie = text.toString()
        }



    }
    val aitext = StringBuilder()

    private fun sendAi() {
        btn_send_ai?.setOnClickListener {
            if (current_distance != null
                && current_speed != null
                && current_heart != null
                && current_calorie != null){

                val logging = HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                }

                val okHttpClient = OkHttpClient.Builder()
                    .addInterceptor(logging)
                    .build()

                val retrofit = Retrofit.Builder()
                    .baseUrl("https://api.coze.cn/v1/")
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()

                val cozeApi = retrofit.create(CozeApi::class.java)
                val parameters = buildParametersSkippingNulls{
                    this["target"] = target
                    this["running"] = running
                    this["targetHeart"] = target_heart
                    this["targetDistance"] = target_distance
                    this["targetSpeed"] = target_speed
                    this["targetCalorie"] = target_calorie
                    this["targetFrequency"] = target_frequency

                    this["currentHeart"] = current_heart
                    this["currentDistance"] = current_distance
                    this["currentSpeed"] = current_speed
                    this["currentCalorie"] = current_calorie
                    this["currentFrequency"] = current_frequency
                }

                val request = CozeRequest(
                    workflowId = "7520463758373027892",
                    parameters = parameters
                )
                val call = cozeApi.runWorkflow(request, "Bearer pat_JG7C6fIyVcpyDjgnyo9w29Y8YX3a1NXX9Rc7lHffka1mSkeowPbk48jvGRJOSS2r")
                call.enqueue(object : Callback<ResponseBody> {
                    override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                        if (response.isSuccessful) {
                            val inputStream = response.body()?.byteStream()
                            val bufferedReader = BufferedReader(InputStreamReader(inputStream))

                            var line: String?

                            // 逐行读取响应流
                            while (bufferedReader.readLine().also { line = it } != null) {
                                // 每一行是一个数据块，通常它们是 key-value 格式
                                try {
                                    // 先简单拆分每个部分的 key-value 数据
                                    val parts = line!!.split(" ")
                                    val id = parts[0].split(":")[1].trim()
                                    val event = parts[1].split(":")[1].trim()
                                    val dataStartIndex = line!!.indexOf("data:") + 5
                                    val dataJson = line!!.substring(dataStartIndex).trim()

                                    // 解析 data 部分
                                    val data = JSONObject(dataJson)

                                    // 打印或处理 id, event, data
                                    println("ID: $id")
                                    println("Event: $event")
                                    println("Data: $data")

                                    // 处理 data 中的字段，例如 content, node_type
                                    val content = data.optString("content", "没有内容")
                                    val nodeType = data.optString("node_type", "没有类型")
                                    println("Content: $content")
                                    println("Node Type: $nodeType")
                                    aitext.append(content)


                                    val runnable = object : Runnable {
                                        override fun run() {
                                            // 显示当前字符
                                            if (currentIndex < aitext.length) {
                                                tv_output_ai?.text = aitext.substring(0, currentIndex + 1)
                                                currentIndex++

                                                // 每 50 毫秒显示下一个字符（可以调整间隔时间）
                                                handler.postDelayed(this, 500)
                                            }
                                        }
                                    }
                                    if (currentIndex == 0) {
                                        handler.post(runnable)
                                    }

                                } catch (e: Exception) {
                                    // 如果出现解析错误，捕获并打印
                                    println("数据解析错误: ${e.message}")
                                }
                            }

                            bufferedReader.close()
                            Log.d("RunningActivity---", "成功: $inputStream")
                        } else {
                            Log.e("RunningActivity---", "错误码: ${response.code()}")
                        }
                    }

                    override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                        Log.e("COZE_ERROR", "网络失败: ${t.message}")
                    }
                })

            }else{
                Toast.makeText(this,"当前数据不能为空",Toast.LENGTH_SHORT).show()
            }
        }
    }




    /**
     * 显示隐藏目标，根据是否设置目标来进行显示有无数据
     * @param target Boolean
     */
    private fun setTarget(targets : Boolean){
        if (targets){
            et_target_distance?.visibility = View.VISIBLE
            et_target_speed?.visibility = View.VISIBLE
            et_target_heart?.visibility = View.VISIBLE
            et_target_calorie?.visibility = View.VISIBLE
            et_target_frequency?.visibility = View.VISIBLE
            tv_target?.visibility = View.VISIBLE

            target_distance = et_target_distance?.text.toString()
            target_speed = et_target_speed?.text.toString()
            target_heart = et_target_heart?.text.toString()
            target_calorie = et_target_calorie?.text.toString()
            target_frequency = et_target_frequency?.text.toString()

        }else{
            et_target_distance?.visibility = View.GONE
            et_target_speed?.visibility = View.GONE
            et_target_heart?.visibility = View.GONE
            et_target_calorie?.visibility = View.GONE
            et_target_frequency?.visibility = View.GONE
            tv_target?.visibility = View.GONE

            target_distance = null
            target_speed = null
            target_heart = null
            target_calorie = null
            target_frequency = null
        }
    }

    private fun buildParametersSkippingNulls(
        block: MutableMap<String, Any?>.() -> Unit
    ): Map<String, Any> {
        val tempMap = mutableMapOf<String, Any?>()
        tempMap.block()
        return tempMap.filterValues { it != null } as Map<String, Any>
    }


}


data class CozeRequest(
    @SerializedName("workflow_id") val workflowId: String,
    val parameters: Map<String, @JvmSuppressWildcards Any>
)

interface CozeApi {
    @POST("workflow/stream_run")
    fun runWorkflow(
        @Body request: CozeRequest,
        @Header("Authorization") authHeader: String = "Bearer pat_JG7C6fIyVcpyDjgnyo9w29Y8YX3a1NXX9Rc7lHffka1mSkeowPbk48jvGRJOSS2r"
    ): Call<ResponseBody>
}
